package com.sina.mysql.utils;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;
import java.math.BigInteger;

/**
 * @ClassName UserBusinessIdentifierGenerator
 * @Description:
 * @Author 段浩杰
 * @Date 2018/8/22 17:40
 * @Version 1.0
 */
public class UserBusinessIdentifierGenerator implements IdentifierGenerator {

    public static final String START_TIME = "1526587134927";

    private static BigIntegerSequence bigIntegerSequence;


    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        UserContext context = UserContextHolder.get();
        if (context == null) {
            throw new HibernateException( "UserContext required" );
        }
        return bigIntegerSequence.next( (Long) context.getUserId() );
    }

    /**
     *
     */
    public static BigInteger next(long userId) {
        return bigIntegerSequence.next( userId );
    }

    public static String nextAsString(long userId) {
        return bigIntegerSequence.nextAsString( userId );
    }


    public static void setBigIntegerSequence(BigIntegerSequence bigIntegerSequence) {
        UserBusinessIdentifierGenerator.bigIntegerSequence = bigIntegerSequence;
    }
}

